package com.demo.delivery.sqlite;

import android.content.Context;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;

import com.demo.delivery.utils.AppUtils;

public class DatabaseHelper extends SQLiteOpenHelper {

    private DatabaseHelper(Context context) {
        super(context, "delivery.db", null, 3);
    }

    public static DatabaseHelper getInstance() {
        return InstanceHolder.instance;
    }

    /**
     * 创建数据表
     * 用户表user：id,username,password
     * 食物购物车表food：user_id,name,img,desc,price,count
     * 订单表order：user_id,pay_time,total_price
     */
    @Override
    public void onCreate(SQLiteDatabase db) {
        String sql = "CREATE TABLE user(id INTEGER PRIMARY KEY AUTOINCREMENT,username TEXT,password TEXT)";
        db.execSQL(sql);
        sql = "CREATE TABLE food(id INTEGER PRIMARY KEY AUTOINCREMENT,user_id INTEGER,name TEXT,img TEXT,'desc' TEXT,price REAL,count INTEGER)";
        db.execSQL(sql);
        sql = "CREATE TABLE 'order'(id INTEGER PRIMARY KEY AUTOINCREMENT,user_id INTEGER,pay_time TEXT,total_price REAL)";
        db.execSQL(sql);
    }

    /**
     * 更新时，删除旧表，创建新表
     */
    @Override
    public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
        String sql = "DROP TABLE IF EXISTS user";
        db.execSQL(sql);
        sql = "DROP TABLE IF EXISTS food";
        db.execSQL(sql);
        sql = "DROP TABLE IF EXISTS 'order'";
        db.execSQL(sql);
        onCreate(db);
    }

    private static final class InstanceHolder {
        static final DatabaseHelper instance = new DatabaseHelper(AppUtils.getApplication());
    }
}
